/*
 * @lc app=leetcode.cn id=112 lang=cpp
 *
 * [112] 路径总和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    bool hasPathSum(TreeNode *root, int targetSum)
    {
        //不需要遍历整棵树 可以有返回值 通过返回值判断
        if (root == NULL)
        {
            return false;
        }
        return traversal(root, targetSum - root->val);
    }
    bool traversal(TreeNode *node, int targetSum)
    {
        if (!node->left && !node->right && targetSum == 0)
        {
            return true;
        }
        if (!node->left && !node->right)
        {
            return false;
        }
        if (node->left)
        {
            targetSum = targetSum - node->left->val;
            if (traversal(node->left, targetSum))
            {
                return true;
            };
            targetSum = targetSum + node->left->val;
        }
        if (node->right)
        {
            targetSum = targetSum - node->right->val;
            if (traversal(node->right, targetSum))
            {
                return true;
            };
            targetSum = targetSum + node->right->val;
        }
        return false;
    }
};
// @lc code=end
